/* eslint-disable */

/**
 * ntko的秘钥信息 后续考虑可以通过接口去获取?
 */
var ntkoInfo = {
  // 32位控件的classid
  classid: 'clsid:A64E3073-2016-4baf-A89D-FFE1FAA10EC2',
  // 64位控件的calssid
  classidx64: 'clsid:A64E3073-2016-4baf-A89D-FFE1FAA10EE2',
  // 谷歌和火狐的classid
  chfixclassid: '{A64E3073-2016-4baf-A89D-FFE1FAA10EE2}',
  // 32位控件包的路径
  codebase: 'officecontrol/ofctnewclsid.cab#version=6,0,1,0',
  // 64位控件包的路径
  codebase64: 'officecontrol/ofctnewclsidx64.cab#version=6,0,1,0',
  // 设置高度
  height: '100%',
  // 设置宽度
  width: '100%',
  // 买断授权密钥如果不是买断可以不用写
  MakerCaption: '上海数慧系统技术有限公司',
  // 买断授权密钥如果不是买断可以不用写
  MakerKey: 'AB377D79A7F9A3BCF2E49CBB5210CC1F2DCE04AD',
  // 密钥
  ProductCaption: '上海数慧系统技术有限公司某某测试用户',
  // 密钥
  ProductKey: '4E4775D17680C526CAA61114667576520CCA4477',
  // 解除时间密钥
  NoExpireKey: '4BBA1B53B15206E78D33846E1420A67B',
  // 插件密钥
  BrowserProductKey: 'D1A445FEECDC83E774C4D3A22C267596661F55B5'
}

/**
 * 初始化 ntko web节点
 */
function initNtko() {
  var box = document.getElementById("box")
  if (box.offsetHeight < 400) {
    return
  }

  // ua.browser 浏览器类型 ua.version 浏览器版本 ua.platform 系统类型
  var ua = util.uaMatch()
  if (!ua.browser) {
    ua.browser = "IE"
  }

  // 1.创建ntko节点 初始化信息
  var objDom = document.createElement("object")
  objDom.setAttribute("class", "tanger-ocx")
  objDom.setAttribute("id", "TANGER_OCX")
  objDom.setAttribute("width", "100%")
  objDom.setAttribute("height", "100%")


  // IE浏览器适配
  if (ua.browser === 'IE') {
    // 系统类型 Win32
    if (ua.platform === 'Win32') {
      objDom.setAttribute("classid", ntkoInfo.classid)
      objDom.setAttribute("codebase", ntkoInfo.codebase)
      objDom.appendChild(util.createDomParams("MakerCaption", "上海数慧系统技术有限公司"))
      objDom.appendChild(util.createDomParams("MakerKey", ntkoInfo.MakerKey))
      objDom.appendChild(util.createDomParams("ProductCaption", ntkoInfo.ProductCaption))
      objDom.appendChild(util.createDomParams("ProductKey", ntkoInfo.ProductKey))
      objDom.appendChild(util.createDomParams("NoExpireKey", ntkoInfo.NoExpireKey))

      objDom.appendChild(util.createDomParams("IsUseUTF8URL", "-1"))
      objDom.appendChild(util.createDomParams("IsUseUTF8Data", "-1"))
      objDom.appendChild(util.createDomParams("Caption", "NTKO OFFICE文档控件示例演示 http://www.ntko.com"))

      var span = document.createElement("span")
      span.setAttribute("style", "color:red")
      span.innerText = "尚未安装NTKO Web 跨浏览器插件"
      objDom.appendChild(span)
    }

    // 系统类型 Win64
    if (ua.platform === 'Win64') {
      objDom.setAttribute("classid", ntkoInfo.classidx64)
      objDom.setAttribute("codebase", ntkoInfo.codebase64)
      objDom.appendChild(util.createDomParams("MakerCaption", "上海数慧系统技术有限公司"))
      objDom.appendChild(util.createDomParams("MakerKey", ntkoInfo.MakerKey))
      objDom.appendChild(util.createDomParams("ProductCaption", ntkoInfo.ProductCaption))
      objDom.appendChild(util.createDomParams("ProductKey", ntkoInfo.ProductKey))
      objDom.appendChild(util.createDomParams("NoExpireKey", ntkoInfo.NoExpireKey))

      objDom.appendChild(util.createDomParams("IsUseUTF8URL", "-1"))
      objDom.appendChild(util.createDomParams("IsUseUTF8Data", "-1"))
      objDom.appendChild(util.createDomParams("Caption", "NTKO OFFICE文档控件示例演示 http://www.ntko.com"))

      var span = document.createElement("span")
      span.setAttribute("style", "color:red")
      span.innerText = "尚未安装NTKO Web 跨浏览器插件"
      objDom.appendChild(span)
    }
  }

  box.appendChild(objDom)
  loadDoc()
}

function loadDoc() {
  var TANGER_OCX_OBJ = document.getElementById("TANGER_OCX")
  isInit = true
  window.TANGER_OCX_OBJ = TANGER_OCX_OBJ
  manage.initUI()

  setTimeout(function () {
    if (paramMap.type === 'material') {
      var url = util.getUploadUrl('projectMaterial/material/' + paramMap.id + '/download',
        {
          fileName: paramMap.fileName,
          mimetype: 'download',
          taskId: paramMap.taskId,
          activityName: paramMap.activityName,
          access_token: paramMap.jwtToken,
        },
        paramMap.baseUrl
      )
      TANGER_OCX_OBJ.OpenFromURL(url, false, "Word.Document")
    }

    if (paramMap.type === 'report') {
      var url = "report/wopi/files/{projectId}/{reportRevisionId}/true/contents?access_token={access_token}"
      url = url.replace('{projectId}', paramMap.projectId)
      url = url.replace('{reportRevisionId}', paramMap.reportRevisionId)
      url = url.replace('{access_token}', paramMap.jwtToken)
      url = util.getUploadUrl(url, {}, paramMap.baseUrl)
      TANGER_OCX_OBJ.OpenFromURL(url, false, "Word.Document")
    }

  }, 100)

  var paramMap = util.getQueryParamMap()

  /**
   * 监听: 打开文档后的
   * @param File
   * @param Document
   * @constructor
   */
  window.OnDocumentOpened = function (File, Document) {
    manage.addCustomButton()
  }

  /**
   * 自定义按钮的任务监听
   * @param ButtonIndex
   * @constructor
   */
  window.OnCustomToolBarCommand = function (ButtonIndex) {
    if (ButtonIndex + '' === '0') {
      /**
       * 材料的存储逻辑
       */
      if (paramMap.type === 'material') {
        /*var apiUrl = "projectMaterial/project/" +
          paramMap.projectId +
          "/material/upload"
        var url = util.getUploadUrl(apiUrl,
          {
            access_token: paramMap.jwtToken,
            directoryInstId: paramMap.directoryInstId,
            taskId: paramMap.taskId,
            activityName: paramMap.activityName
          },
          paramMap.baseUrl)*/
        var apiUrl = "projectMaterial/material/update"
        var url = util.getUploadUrl(apiUrl,
          {
            access_token: paramMap.jwtToken,
            materialId: paramMap.id,
            projectId: paramMap.projectId,
            taskId: paramMap.taskId
          },
          paramMap.baseUrl)
        manage.saveToURL(url, "file", paramMap.fileName, true)
      }
      /**
       * 报表的存储逻辑
       */
      if (paramMap.type === 'report') {
        var url = "report/wopi/report/file/contents"
        url = util.getUploadUrl(url,
          {
            access_token: paramMap.jwtToken,
            projectId: paramMap.projectId,
            reportRevisionId: paramMap.reportRevisionId
          },
          paramMap.baseUrl)
        manage.saveToURL(url, "file", 'test.docx', true)
      }
    }

    if (ButtonIndex + '' === '1') {
      util.showConfirm("将清除缓存并重新加载,您的修改可能丢失,是否继续", "重置",
        function () {
          clearCache(paramMap)
          loadDoc()
        })
    }

  }
}
function clearCache(paramMap){
  var url = "report/wopi/delete/files/" + paramMap.projectId + "/" + paramMap.reportRevisionId
  url = util.getUploadUrl(url, {access_token: paramMap.jwtToken}, paramMap.baseUrl)
  TANGER_OCX_OBJ.DoWebExecute2(url)
}

/**
 * ntko管理
 * @type {{}}
 */
var manage = {
  /**
   * 初始化ntko的UI
   */
  initUI: function () {
    if (window.navigator.platform + '' === "Win64") {
      TANGER_OCX_OBJ.AddDocTypePlugin(".tif", "tif.NtkoDocument", "4.0.0.2", "/OfficeControl/ntkooledocallx64.cab", 51, true);
      TANGER_OCX_OBJ.AddDocTypePlugin(".pdf", "PDF.NtkoDocument", "4.0.0.2", "/OfficeControl/ntkooledocallx64.cab", 51, true);
      TANGER_OCX_OBJ.AddDocTypePlugin(".tiff", "TIF.NtkoDocument", "4.0.0.1", "/OfficeControl/ntkooledocallx64.cab", 52, true);
    } else {
      TANGER_OCX_OBJ.AddDocTypePlugin(".pdf", "PDF.NtkoDocument", "4.0.0.2", "/OfficeControl/ntkooledocall.cab", 51, true);
      TANGER_OCX_OBJ.AddDocTypePlugin(".tif", "tif.NtkoDocument", "4.0.0.2", "/OfficeControl/ntkooledocall.cab", 51, true);
      TANGER_OCX_OBJ.AddDocTypePlugin(".tiff", "TIF.NtkoDocument", "4.0.0.1", "/OfficeControl/ntkooledocall.cab", 52, true);
    }
    // 全屏展示
    TANGER_OCX_OBJ.FullScreenMode = false
    // 禁用全屏按钮
    TANGER_OCX_OBJ.IsShowFullScreenButton = false
    // 禁用双击缩放全屏
    TANGER_OCX_OBJ.IsEnableDoubleClickFSM = false

    TANGER_OCX_OBJ.Menubar = true
    TANGER_OCX_OBJ.FileNew = false
    TANGER_OCX_OBJ.FileOpen = false
    TANGER_OCX_OBJ.FilePrint = false
    TANGER_OCX_OBJ.FileSave = false
    TANGER_OCX_OBJ.Menubar = false
  },
  /**
   * 添加自定义的按钮
   */
  addCustomButton: function () {
    if(!TANGER_OCX_OBJ.CustomToolBar){
      TANGER_OCX_OBJ.CustomToolBar = true
      TANGER_OCX_OBJ.AddCustomToolButton("保存", 5)
      TANGER_OCX_OBJ.AddCustomToolButton("重置", 12)
    }
  },
  /**
   * 通过url保存文件
   * @param url url地址
   * @param fieldName url接口文件变量名
   * @param fileName 文件名
   * @param showProgress 是否显示进度条
   */
  saveToURL: function (url, fieldName, fileName, showProgress) {
    TANGER_OCX_OBJ.SaveToURL(url, fieldName, '', fileName, 0, showProgress)
  }
}

/**
 * 工具类统一管理
 */
var util = {
  /**
   * 显示提示信息
   * @param content 提示内容
   * @param title 标题 可空 默认为提示
   */
  showMessage: function (content, title) {
    if (!title) {
      title = '提示'
    }
    TANGER_OCX_OBJ.ShowTipMessage(title, content)
  },
  showConfirm: function (content, title, callback) {
    if (!title) {
      title = '提示'
    }
    var isAccept = TANGER_OCX_OBJ.ShowConfirmMessage(title, content, false, true)
    if (isAccept) {
      callback()
    }
  },
  /**
   * 获取当前系统信息
   */
  uaMatch: function () {
    var ua = navigator.userAgent.toLowerCase()
    var rMsie = /(msie\s|trident.*rv:)([\w.]+)/
    var rFirefox = /(firefox)\/([\w.]+)/
    var rOpera = /(opera).+version\/([\w.]+)/
    var rChrome = /(chrome)\/([\w.]+)/
    var rSafari = /version\/([\w.]+).*(safari)/
    var match = rMsie.exec(ua)
    var result = {}
    if (match != null) {
      result = {browser: 'IE', version: match[2] || '0'}
    }
    var firefoxmatch = rFirefox.exec(ua)
    if (firefoxmatch != null) {
      result = {browser: firefoxmatch[1] || '', version: firefoxmatch[2] || '0'}
    }
    var operamatch = rOpera.exec(ua)
    if (operamatch != null) {
      result = {browser: operamatch[1] || '', version: operamatch[2] || '0'}
    }
    var chromematch = rChrome.exec(ua)
    if (chromematch != null) {
      result = {browser: chromematch[1] || '', version: chromematch[2] || '0'}
    }
    var safarimatch = rSafari.exec(ua)
    if (safarimatch != null) {
      result = {browser: safarimatch[2] || '', version: safarimatch[1] || '0'}
    }
    if (match != null) {
      result = {browser: '', version: '0'}
    }
    result.platform = window.navigator.platform
    return result
  },
  /**
   * 创建param元素
   * @param name
   * @param value
   * @returns {HTMLParamElement}
   */
  createDomParams: function (name, value) {
    var dom = document.createElement("param")
    dom.setAttribute("name", name)
    dom.setAttribute("value", value)
    return dom
  },
  /**
   * 获取当前窗口的参数
   * @returns {{}}
   */
  getQueryParamMap: function () {
    var href = window.location.href
    var sub = href.substring(href.indexOf("?") + 1)
    var subList = sub.split("&")
    var result = {}
    subList.forEach(function (item) {
      var infoList = item.split("=")
      result[infoList[0]] = decodeURI(infoList[1] || '')
    })
    return result
  },
  /**
   * 获取上传地址
   * @param urlSuff 上传接口的相对url地址 不需要以 / 开头
   * @param params 额外参数 {}
   * @param baseUrl 基础地址 若不传递则将取 location.origin + location.pathname
   */
  getUploadUrl: function (urlSuff, params, baseUrl) {
    if (!baseUrl) {
      baseUrl = location.origin + location.pathname
    }
    var url = baseUrl + urlSuff
    var index = 0
    Object.keys(params).forEach(function (key) {
      if (params[key]) {
        if (index === 0) {
          url += '?'
        } else {
          url += '&'
        }
        url += key + '=' + encodeURI(params[key] || '')
        index++
      }

    })
    return url
  }

}


